package com.summer.container;

import java.lang.reflect.Array;

public class ArrayTest {

	
	public static void main(String[] args) {
		
		Mode[] modes = new Mode[] {new Mode("summer"), new Mode("summer1"), new Mode("summer2"), new Mode("summer3"), new Mode("summer4")};//{1, 2, 3, 4, 5};
		String[] aa = ArrayTest.<String, Mode>transformAll(modes, data -> data.name);
		if(aa != null) {
			for(String str : aa) {
				System.out.println(str);
			}
		}
		
		String[] aa1 = {"ss1", "ss2", "ss3", "ss4", "ss5"};
		Mode[] modes1 = ArrayTest.<Mode, String>transformAll(aa1, data -> new Mode(data));
		if(modes1 != null) {
			for(Mode mode : modes1) {
				System.out.println(mode.name);
			}
		}
		
		Integer[] b = {1, 2, 3, 4, 5};
		String[] bb = ArrayTest.<String, Integer>transformAll(b, data -> String.valueOf(data)+"sss");
		if(bb != null) {
			for(String str : bb) {
				System.out.println(str);
			}
		}
		
		String[] b1 = {"1", "2", "3", "4", "5"};
		Integer[] bb1 = ArrayTest.<Integer, String>transformAll(b1, data -> Integer.valueOf(data));
		if(bb1 != null) {
			for(int i : bb1) {
				System.out.println(i);
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static <R, T> R[] transformAll(T[] array, Transformer<R, T> t) {
        if (array == null) {
            return null;
        }
        R[] result = null;
        for (int i = 0; i < array.length; i++) {
            R data = t.transform(array[i]);
            if(data != null) {
                if(result == null) {
                    result = (R[]) Array.newInstance(data.getClass(), array.length);
                }
                result[i] = t.transform(array[i]);
            }
        }
        return result;
    }
	
	public interface Transformer<R, T> {
		R transform(T t);
	}
	
	public static class Mode {
		public final String name;
		public Mode(String name) {
			this.name = name;
		}
	}
	
}
